<template>
  <div id="course-structure-edit">
    <el-form ref="form" label-width="80px">
      <div style="display: flex;flex-direction: column">
        <div style="width: 100%;justify-content: flex-end;flex-direction: row;display: flex;margin-bottom: 20px">
          <el-button type="primary" @click="beginAddChapter">添加章</el-button>
        </div>
        <div v-for="(chapter, chapterIndex) in chapters" :key="chapter.id">
          <div
              style="display: flex;flex-direction: row;justify-content: space-between;align-items: center;width: 100%;background-color: #d2d2d2;height: 80px">
            <el-form-item label="章名称" style="width: 600px;margin-bottom: 0">
              <el-input v-model="chapter.name" disabled></el-input>
            </el-form-item>
            <div style="width: 600px;justify-content: flex-end;flex-direction: row;display: flex;margin-right: 20px">
              <el-button type="primary" @click="beginAddSection(chapter.id)">添加节</el-button>
              <el-button type="primary" @click="updateChapterName(chapter.id)">编辑</el-button>
              <el-button @click="removeChapter(chapter.id)" type="danger">删除</el-button>
              <el-button v-if="chapterIndex !== 0" @click="upChapter(chapter.id)">上移</el-button>
            </div>
          </div>
          <div v-for="(section, sectionIndex) in chapter.sections" :key="section.id">
            <div
                style="display: flex;flex-direction: row;justify-content: space-between;align-items: center;width: 90%;margin-left:10%;background-color: #dedede;height: 80px">
              <el-form-item label="节名称" style="width: 600px;margin-bottom: 0">
                <el-input style="width: 400px" v-model="section.name" disabled></el-input>
              </el-form-item>
              <div style="width: 400px;justify-content: flex-end;flex-direction: row;display: flex;margin-right: 20px">
                <el-button type="primary" @click="beginAddSectionContent(section.sectionId)">添加课时</el-button>
                <el-button type="primary" @click="updateSectionName(section.sectionId)">编辑</el-button>
                <el-button type="primary" @click="showSection(section)">预览</el-button>
                <el-button @click="removeSection(section.sectionId)" type="danger">删除</el-button>
                <el-button v-if="sectionIndex !== 0" @click="upSection(section.sectionId)">上移</el-button>
              </div>
            </div>
            <div v-for="(sectionContent,sectionContentIndex) in section.sectionContents" :key="sectionContent.id">
              <div
                  style="display: flex;flex-direction: row;justify-content: space-between;align-items: center;width: 80%;margin-left:20%;background-color: #f3f3f3;height: 80px">
                <el-form-item label="课时名称" style="width: 600px;margin-bottom: 0">
                  <el-input v-if="sectionContentIndex === 0" value="本节介绍" disabled></el-input>
                  <el-input v-else v-model="sectionContent.name" disabled></el-input>
                </el-form-item>
                <div
                    style="width: 400px;justify-content: flex-end;flex-direction: row;display: flex;margin-right: 20px">
                  <el-button type="primary" @click="beginEditSectionContent(sectionContent)">编辑</el-button>
                  <el-button @click="removeSectionContent(sectionContent.id)" type="danger">删除</el-button>
                  <el-button v-if="sectionContentIndex !== 0" @click="upSectionContent(sectionContent.id)">上移
                  </el-button>
<!--                  <el-button v-if="sectionContent.version>0" @click="rollbackSectionContent(sectionContent)"> 回滚({{sectionContent.version}})</el-button>-->
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>

      <el-dialog title="新增章" :visible.sync="addChapterVisible">
        <el-form ref="form" label-width="80px">
          <el-form-item label="章名称" style="width: 630px;">
            <el-input v-model="chapterAddInput.name"></el-input>
          </el-form-item>
          <WangEditor :intro-html="chapterAddInput.linkSectionContent.content"
                      @setIntroduction="setChapterSectionContentContent"/>
          <div style="display: flex;flex-direction: row;justify-content: center;align-items: center;margin-top: 20px">
            <el-button type="primary" @click="addChapter()">新增章</el-button>
          </div>
        </el-form>
      </el-dialog>
      <el-dialog title="增加节" :visible.sync="addSectionVisible">
        <el-form ref="form" label-width="80px">
          <el-form-item label="章节名称" style="width: 630px;">
            <el-input v-model="sectionAddInput.name"></el-input>
          </el-form-item>
          <el-form-item label="章节类型" style="width: 630px;">
            <el-select v-model="sectionAddInput.type" placeholder="选择章节类型">
              <el-option v-for="item in sectionType" :key="item.type" :value="item.type" :label="item.label">
              </el-option>
            </el-select>
          </el-form-item>
          <div v-if="sectionAddInput.type === 0">
            <WangEditor :intro-html="sectionAddInput.linkSectionContent.content"
                        @setIntroduction="setSectionContentContent"/>
          </div>

          <el-form-item v-if="sectionAddInput.type === 1" label="已有测试" style="width: 600px;margin-top: 20px">
            <el-select v-model="sectionAddInput.linkId" value-key="description" :remote-method="examQuery"
                       :loading="loading"
                       filterable remote reserve-keyword placeholder="请输入关键词" style="width: 600px">
              <el-option
                  v-for="item in examQueryList" :key="item" :label="item.title" :value="item.id">
              </el-option>
            </el-select>
          </el-form-item>

          <div style="display: flex;flex-direction: row;justify-content: center;align-items: center;margin-top: 20px">
            <el-button type="primary" @click="addSection()">新增章节</el-button>
          </div>
        </el-form>
      </el-dialog>
      <el-dialog title="编辑课时" :visible.sync="dialogTableVisible">
        <el-form ref="form" label-width="80px">

          <el-form-item v-if="currentSectionContent.id" label="课时id" style="width: 630px;">
            <el-input v-model="currentSectionContent.id" disabled></el-input>
          </el-form-item>

          <el-form-item label="课时名称" style="width: 630px;">
            <el-input v-model="currentSectionContent.name"></el-input>
          </el-form-item>

          <el-form-item label="课时类型" style="width: 630px;">
            <el-select v-model="currentSectionContent.type" placeholder="选择课时类型">
              <el-option v-for="item in resourceType" :key="item.type" :value="item.type" :label="item.label">
              </el-option>
            </el-select>
          </el-form-item>

          <div v-if="currentSectionContent.type === 0">
            <WangEditor :intro-html="currentSectionContent.content" @setIntroduction="setContent"/>
          </div>

          <div v-else>
            <el-form-item label="绑定方式" style="width: 630px;">
              <el-select v-model="bindWay" placeholder="选择资源来源">
                <el-option value="0" label="选择已有资源"></el-option>
                <el-option value="1" label="上传新资源"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item v-if="bindWay == 0" label="已有资源" style="width: 600px;margin-top: 20px">
              <el-select v-model="currentResource" value-key="name" :remote-method="resourceQuery"
                         :loading="loading"
                         filterable remote reserve-keyword placeholder="请输入关键词" style="width: 600px">
                <el-option v-if="currentSectionContent.type === 1" v-for="item in resourceList" :key="item"
                           :label="item.name" :value="item">
                </el-option>
                <el-option v-if="currentSectionContent.type === 2" v-for="item in resourceList" :key="item"
                           :label="item.description" :value="item">
                </el-option>
              </el-select>
            </el-form-item>
            <div v-else>
              <el-form-item label="资源id" style="width: 630px;">
                <el-input v-model="currentSectionContent.content" disabled></el-input>
              </el-form-item>
              <!-- 上传视频 -->
              <div v-if="currentSectionContent.type === 1"
                   style="width: 80%;margin-left: 10%;background-color: #e8e8e8;border-radius: 5px">
                <UploadAuthVue :filename="fileName" @getResourceId="getResourceId"></UploadAuthVue>
              </div>
              <!-- 新建题目 -->
              <div v-if="currentSectionContent.type === 2"
                   style="width: 80%;margin-left: 10%;background-color: #e8e8e8;border-radius: 5px;padding: 10px 0">
                <el-form-item label="题目描述" style="width: 600px;">
                  <el-input v-model="problemAddInput.description"></el-input>
                </el-form-item>
                <el-form-item label="题目选项" style="width: 600px;">
                  <el-button type="primary" @click="addOption()">添加选项</el-button>
                  <div v-for="(option,index) in problemAddInput.options" :key="index">
                    <div
                        style="display: flex;flex-direction: row;justify-content: space-between;align-items: center;background-color: #efefef;height: 60px;border-radius: 10px;margin-top: 10px">
                      <el-form-item label="选项内容" style="width: 600px;margin-bottom: 0">
                        <el-input v-model="option.content"></el-input>
                      </el-form-item>
                      <div
                          style="width: 400px;justify-content: flex-end;flex-direction: row;display: flex;margin-right: 20px">
                        <el-button @click="removeOption(index)" type="danger">删除</el-button>
                      </div>
                    </div>
                  </div>
                </el-form-item>
                <el-form-item label="正确答案" style="width: 400px;">
                  <el-select v-model="problemAddInput.answer" value-key="content" filterable placeholder="请输入关键词"
                             style="width: 400px">
                    <el-option
                        v-for="(item,index) in problemAddInput.options" :key="item.content" :label="item.content"
                        :value="index">
                    </el-option>
                  </el-select>
                </el-form-item>
                <div
                    style="display: flex;flex-direction: row;justify-content: center;align-items: center;margin-top: 20px">
                  <el-button type="primary" v-if="currentSectionContent.content === ''" @click="saveProblem()">
                    上传题目
                  </el-button>
                </div>
              </div>
            </div>
          </div>


          <div style="display: flex;flex-direction: row;justify-content: center;align-items: center;margin-top: 20px">
            <el-button type="primary" @click="saveOrUpdateSectionContent()">保存课时</el-button>
          </div>
        </el-form>
      </el-dialog>
      <el-dialog title="章节预览" :visible.sync="sectionShowVisible">
        <h2>{{ currentSection.name }}</h2>
        <div style="width: 300px;background-color: #FAFAFA;padding: 20px;" v-for="(content,index) in currentSection.sectionContents">
          <h3 v-if="index === 0">本节介绍</h3>
          <h3 v-else>{{ content.name }}</h3>
          <div v-if="content.type === 0">
            <div v-html="content.content"></div>
          </div>
          <div v-if="content.type === 1">
            <div>
              <vue-aliplayer-v2
                  @ready="handleReady"
                  @play="handlePlay"
                  @pause="handlePause"
                  @completeSeek="handleCompleteSeek"
                  ref="VueAliplayerV2"
                  @timeupdate="handleTimeupdate"
                  :options="{
                    vid: content.video.oss,
                    playauth: content.video.auth,
                    height: '170px',
                    width: '300px',
                    disableSeek: false,
                  }"
              />
            </div>
          </div>
          <div v-if="content.type === 2">
            <div class="question">
              <div class="content">{{ content.problem.description }}</div>
              <div class="options">
                <div class="option" v-for="(v, k) in content.problem.options" :key="v">
                  <input type="radio" name="dialogQ" :id="v + '-' + k" :value="k" v-model="dialogChosen"
                         style="display: none"/>
                  <label :for="v + '-' + k">
                  <span :class="[  'chose-icon', content.problem.type === 0 ? 'circle' : 'squire',
                    { chosen: dialogChosen === k},
                    { wrong: isWrong(dialogChosen,content.problem.answer) },]"></span>
                    <span class="text">{{ k }}. {{ v }}</span>
                  </label>
                </div>
              </div>
            </div>
          </div>
        </div>
      </el-dialog>
    </el-form>
  </div>
</template>

<script>

import WangEditor from "@/components/WangEditor.vue";
import UploadAuthVue from "@/components/UploadAuth.vue";
import OssUploader from "@/components/OssUploader.vue";

export default {
  name: "CourseStructureEdit",
  // eslint-disable-next-line vue/no-unused-components
  components: {UploadAuthVue, OssUploader, WangEditor},
  data() {
    return {
      course:{},
      loading: false,
      // 课程结构信息
      chapters: [],

      rollbackSectionContentData:{
        sectionId : '',
        sectionContentId : '',
        versionDescription : ''
      },

      addChapterVisible: false,
      chapterAddInput: {
        linkSectionContent: {
          type: 0,
          sequence: 0
        }
      },

      addSectionVisible: false,
      sectionAddInput: {
        linkSectionContent: {
          type: 0,
          sequence: 0
        }
      },
      sectionType: [
        {
          type: 0,
          label: '富媒体'
        }, {
          type: 1,
          label: '限时测试'
        }
      ],


      sectionShowVisible: false,
      currentSection: {},// 当前选择的节



      dialogTableVisible: false,

      currentSectionContent: {
        content: '',
      },// 存当前绑定的节内容参数

      bindWay: "0",
      resourceType: [{
        type: 0,
        label: '富文本'
      }, {
        type: 1,
        label: '视频'
      }, {
        type: 2,
        label: '题目'
      }],
      resourceNameKey: "",
      resourceList: [],
      currentResource: {},// 当前选择的资源
      examQueryList: [],


      fileName: '',
      dialogChosen: '',
      problemAddInput: {
        description: "",
        options: [],
        answer: null
      },
    }
  },

  mounted() {
    if (this.$route.params && this.$route.params.id) {
      this.course.id = this.$route.params.id
      this.getBindAllInfo()
    }
  },

  methods: {
    // 获取每节信息和已绑定课时信息
    getBindAllInfo() {
      this.$api.getBindAllInfo({courseId: this.course.id})
          .then(res => {
            this.chapters = res.data.chapters
          })
    },


    // 视频或题目查询
    resourceQuery(nameKey) {
      if (this.currentSectionContent.type === 1) {
        this.$api.queryVideo({
          nameKey: nameKey
        }).then(response => {
          this.resourceList = response.data.rows
        })
      } else {
        this.$api.queryProblem({
          description: nameKey
        }).then(response => {
          this.resourceList = response.data
        })
      }
    },
    getResourceId(resourceId) {
      this.currentSectionContent.content = resourceId
    },



    // 增加题目选项
    addOption() {
      this.problemAddInput.options.push({
        content: ""
      })
    },
    // 移除题目选项
    removeOption(index) {
      this.problemAddInput.options.splice(index, 1)
    },
    // 保存并获取题目信息
    saveProblem() {
      let answer = ""
      let options = []
      for (let i = 0; i < this.problemAddInput.options.length; i++) {
        if (this.problemAddInput.answer === i) {
          answer = answer + "1"
        } else {
          answer = answer + "0"
        }
        options.push(this.problemAddInput.options[i].content)
      }
      this.problemAddInput.answer = parseInt(answer, 2);
      this.problemAddInput.type = 0
      this.problemAddInput.options = options


      this.$api.saveOrUpdateProblem(this.problemAddInput)
          .then(res => {
            this.$message.success("成功" + res.data)
            this.problemAddInput = {
              progress: 0,
              description: this.problemAddInput.description,
              id: res.data
            }
          })
    },








    // 新增章
    beginAddChapter() {
      this.addChapterVisible = true
      this.chapterAddInput.courseId = this.course.id
      this.chapterAddInput.linkSectionContent.courseId = this.course.id
    },
    addChapter() {
      this.$api.addChapter(this.chapterAddInput).then(() => {
        this.getBindAllInfo()
        this.addChapterVisible = false
      })
    },
    // 新增节
    beginAddSection(chapterId) {
      this.addSectionVisible = true
      this.sectionAddInput.courseId = this.course.id
      this.sectionAddInput.chapterId = chapterId
      this.sectionAddInput.linkSectionContent.courseId = this.course.id
    },
    addSection() {
      this.$api.addSection(this.sectionAddInput).then(() => {
        this.getBindAllInfo()
        this.addSectionVisible = false
      })
    },
    examQuery(title) {
      this.$api.listExam({
        title
      }).then(response => {
        this.examQueryList = response.data
        console.log(this.examQueryList)
      })
    },
    // 新增课时
    beginAddSectionContent(sectionId) {
      this.currentSectionContent.sectionId = sectionId
      this.dialogTableVisible = true
    },
    // 编辑课时
    beginEditSectionContent(sectionContent) {
      this.currentSectionContent = sectionContent
      this.dialogTableVisible = true
    },
    saveOrUpdateSectionContent() {
      // 插入主对象
      if (this.bindWay === "0" && this.currentSectionContent.type !== 0) {
        this.currentSectionContent.content = this.currentResource.id
      }
      this.currentSectionContent.published = this.currentSectionContent.published ? 1 : 0


      console.log(this.currentSectionContent)

      if(this.currentSectionContent.id){
        // 修改课时
        this.$api.updateSectionContent(this.currentSectionContent).then(() => {
          this.$message.success("成功")
          this.getBindAllInfo()
        })
      }else{
        // 新增课时
        this.$api.addSectionContent(this.currentSectionContent).then(() => {
          this.$message.success("成功")
          this.getBindAllInfo()
        })
      }
      this.currentSectionContent = {
        sectionId: '',
        name: '',
        type: '',
        content: '',
        published: 0
      }
      this.dialogTableVisible = false
    },

    // 改章名
    updateChapterName(chapterId) {
      this.$prompt('请输入章名称', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
      }).then(({value}) => {
        this.$api.updateChapterName({
          chapterName: value,
          chapterId
        }).then(() => {
          this.$message.success("成功")
          this.getBindAllInfo(this.course.id)
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '取消'
        });
      });
    },
    // 改节名
    updateSectionName(sectionId) {
      this.$prompt('请输入节名称', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
      }).then(({value}) => {
        this.$api.updateSectionName({
          sectionName: value,
          sectionId
        }).then(() => {
          this.$message.success("成功")
          this.getBindAllInfo(this.course.id)
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '取消'
        });
      });
    },
    // 改课时名
    updateSectionContentName(sectionContentId) {
      this.$prompt('请输入节名称', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
      }).then(({value}) => {
        this.$api.updateSectionContentName({
          sectionContentName: value,
          sectionContentId
        }).then(() => {
          this.$message.success("成功")
          this.getBindAllInfo(this.course.id)
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '取消'
        });
      });
    },

    // 移除一个章
    removeChapter(chapterId) {
      this.$api.removeChapter({
        chapterId
      }).then(() => {
        this.$message.success("成功")
        this.getBindAllInfo(this.course.id)
      })
    },
    // 移除一个节
    removeSection(sectionId) {
      this.$api.removeSection({
        sectionId
      }).then(() => {
        this.$message.success("成功")
        this.getBindAllInfo(this.course.id)
      })
    },
    // 移除一个课时
    removeSectionContent(sectionContentId) {
      this.$api.removeSectionContent({
        sectionContentId
      }).then(() => {
        this.$message.success("成功")
        this.getBindAllInfo(this.course.id)
      })
    },
    // 移除题目
    removeProblem(sectionContentId, progress) {
      this.$api.removeProblem({
        sectionContentId,
        progress
      }).then(() => {
        this.$message.success("成功")
        this.getBindAllInfo(this.course.id)
      })
    },

    // 上移一个章
    upChapter(chapterId) {
      this.$api.upChapter({
        chapterId
      }).then(() => {
        this.$message.success("成功")
        this.getBindAllInfo(this.course.id)
      })
    },
    // 上移一个节
    upSection(sectionId) {
      this.$api.upSection({
        sectionId
      }).then(() => {
        this.$message.success("成功")
        this.getBindAllInfo()
      })
    },
    // 上移一个测试
    upExam(examId) {
      this.$api.upExam({
        examId
      }).then(() => {
        this.$message.success("成功")
        this.getBindAllInfo(this.course.id)
      })
    },
    // 上移一个课时
    upSectionContent(sectionContentId) {
      this.$api.upSectionContent({
        sectionContentId
      }).then(() => {
        this.$message.success("成功")
        this.getBindAllInfo(this.course.id)
      })
    },


    // 前往更新一个测试的内容
    toUpdateExam(examId) {
      this.$router.push({
        path: '/course/exam-add',
        query: {examId}
      })
    },

    // 节预览
    showSection(section) {
      this.currentSection.name = section.name
      console.log("节信息", section)
      // 获取本节的所有课时
      this.$api.querySectionContentBySectionId({
        sectionId: section.sectionId
      }).then(res => {
        console.log("返回值", res.data)
        this.currentSection.sectionContents = res.data
        this.sectionShowVisible = true
      })

    },

    // 播放器事件回调
    handleReady(e) {
      console.log(`ready`, e);
    },
    handlePlay() {
    },
    handlePause() {
    },
    handleCompleteSeek() {
    },
    handleTimeupdate() {

    },

    // 题目判断
    isWrong(answer, rightAnswer) {
      console.log("判断", rightAnswer, answer)
      return parseInt(rightAnswer) !== parseInt(answer)
    },

    // 富文本内容处理
    setContent: function (html) {
      this.currentSectionContent.content = html;//在父组件修改值
    },
    setSectionContentContent: function (html) {
      this.sectionAddInput.linkSectionContent.content = html;//在父组件修改值
    },
    setChapterSectionContentContent: function (html) {
      this.chapterAddInput.linkSectionContent.content = html;//在父组件修改值
    },

    /*****回滚相关**********/
    rollbackSectionContent(rollbackSectionContentData){
      this.$confirm('此操作回将滚小节内容至上一次版本, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'error'
      }).then(() => {
        this.$api.rollbackSectionContent(rollbackSectionContentData).then(res => {
          this.$message({
            type: 'success',
            message: '回滚成功!'
          })
          this.getBindAllInfo()
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消回滚'
        });
      });
    }
  },
}
</script>

<style scoped lang="scss">
#course-structure-edit {
  width: 100%;
  margin-bottom: 20px;
}
</style>
